package cool.zhang.controller;
import cool.zhang.model.Movie;
import cool.zhang.repository.MovieDao;
import cool.zhang.repository.MovieMapper;
import cool.zhang.repository.MovieRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class MovieController {
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private MovieRepository movieRepository;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String,String> valueOperations;

    @Autowired
    private MovieDao movieDao;

    @Autowired
    private MovieMapper movieMapper;

    @RequestMapping(value = "/addMovie",method = RequestMethod.POST)
    public String saveMovie(Movie movie){
        movieRepository.save(movie);
        System.out.println(movie.getId());
        return "success";
    }

    @RequestMapping("/set")
    public String setKeyAndValue(String key,String value){
        logger.debug("设置set:key={},value={}",key,value);
        valueOperations.set(key, value);

        return "Set OK";
    }

    @RequestMapping("/get")
    public String getKey(String key){
        logger.debug("访问get:key={}",key);
        return valueOperations.get(key);
    }

    @RequestMapping("/setMovies")
    public String setMovies(){
        List<Movie> movies = movieRepository.findAll();
        if (CollectionUtils.isEmpty(movies))
        {
            return "Has none";
        }

        for (Movie movie:movies) {
            movieDao.save(movie);
        }

        return "success";
    }

    @RequestMapping("/getMovie")
    public Movie getMovie(Integer id){
        return movieDao.getMovie(id);
    }

    @RequestMapping("/getAllMovies")
    public List<Movie> getAllMovies(){
        return movieMapper.findAllMovies();
    }
}
